package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.dto.LeaderRegisterDTO;
import org.example.backend.entity.Commission;
import org.example.backend.entity.Leader;
import org.example.backend.entity.Order;
import org.example.backend.entity.User;
import org.example.backend.entity.view.CommissionStatsView;
import org.example.backend.entity.view.LeaderOrderStatsView;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.CommissionMapper;
import org.example.backend.mapper.LeaderMapper;
import org.example.backend.mapper.OrderMapper;
import org.example.backend.mapper.UserMapper;
import org.example.backend.mapper.view.CommissionStatsViewMapper;
import org.example.backend.mapper.view.LeaderOrderStatsViewMapper;
import org.example.backend.util.MD5Util;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团长管理控制器
 * 提供团长查询、新增、修改、删除等功能
 */
@RestController
@RequestMapping("/leader")
public class LeaderController {

    @Autowired
    private LeaderMapper leaderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LeaderOrderStatsViewMapper leaderOrderStatsViewMapper;

    @Autowired
    private CommissionStatsViewMapper commissionStatsViewMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CommissionMapper commissionMapper;

    /**
     * 分页查询团长列表
     * @param current 当前页码
     * @param size 每页大小
     * @param name 团长姓名（可选，模糊查询）
     * @param phone 联系电话（可选，模糊查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<Leader>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer status) {

        Page<Leader> page = new Page<>(current, size);

        LambdaQueryWrapper<Leader> queryWrapper = Wrappers.<Leader>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Leader::getName, name)
                .like(StringUtils.isNotBlank(phone), Leader::getPhone, phone)
                .eq(status != null, Leader::getStatus, status)
                .orderByDesc(Leader::getCreateTime);

        Page<Leader> leaderPage = leaderMapper.selectPage(page, queryWrapper);

        return ResponseUtil.success(new PageResult<>(leaderPage.getTotal(), leaderPage.getRecords()));
    }

    /**
     * 获取团长详情
     * @param id 团长ID
     * @return 团长详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Leader>> getById(@PathVariable Long id) {
        Leader leader = leaderMapper.selectById(id);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }
        return ResponseUtil.success(leader);
    }

    /**
     * 团长注册（包含用户创建和团长创建）
     * @param registerDTO 注册信息
     * @return 操作结果
     */
    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
    public ResponseEntity<Result<Void>> register(@Valid @RequestBody LeaderRegisterDTO registerDTO) {
        try {
            if (StringUtils.isBlank(registerDTO.getUsername()) || StringUtils.isBlank(registerDTO.getPassword())) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "用户名和密码不能为空");
            }
            
            // 检查用户名是否已存在
            Long usernameCount = userMapper.selectCount(
                Wrappers.<User>lambdaQuery()
                    .eq(User::getUsername, registerDTO.getUsername())
                    .last("FOR UPDATE")
            );
            if (usernameCount > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "用户名已存在");
            }
            
            // 检查手机号是否已存在
            Long phoneCount = userMapper.selectCount(
                Wrappers.<User>lambdaQuery()
                    .eq(User::getPhone, registerDTO.getPhone())
                    .last("FOR UPDATE")
            );
            if (phoneCount > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "手机号已被注册");
            }
            
            // 创建用户账号
            User user = new User();
            user.setUsername(registerDTO.getUsername());
            user.setPassword(MD5Util.encrypt(registerDTO.getPassword()));
            user.setPhone(registerDTO.getPhone());
            user.setRole("leader");
            user.setStatus(1); // 默认启用
            userMapper.insert(user);
            
            // 创建团长信息
            Leader leader = new Leader();
            leader.setUserId(user.getId());
            leader.setName(registerDTO.getName());
            leader.setPhone(registerDTO.getPhone());
            leader.setAddress(registerDTO.getAddress());
            leader.setStatus(1); // 默认启用
            
            leaderMapper.insert(leader);
            return ResponseUtil.created();
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ResultCode.SERVER_ERROR, "团长注册失败: " + e.getMessage());
        }
    }

    /**
     * 新增团长
     * @param registerDTO 团长信息
     * @return 操作结果
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
    public ResponseEntity<Result<Void>> save(@Valid @RequestBody LeaderRegisterDTO registerDTO) {
        try {
            if (StringUtils.isBlank(registerDTO.getUsername()) || StringUtils.isBlank(registerDTO.getPassword())) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "用户名和密码不能为空");
            }
            
            // 检查用户名是否已存在
            Long usernameCount = userMapper.selectCount(
                Wrappers.<User>lambdaQuery()
                    .eq(User::getUsername, registerDTO.getUsername())
                    .last("FOR UPDATE")
            );
            if (usernameCount > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "用户名已存在");
            }
            
            // 检查手机号是否已存在
            Long phoneCount = userMapper.selectCount(
                Wrappers.<User>lambdaQuery()
                    .eq(User::getPhone, registerDTO.getPhone())
                    .last("FOR UPDATE")
            );
            if (phoneCount > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "手机号已被注册");
            }
            
            // 创建用户账号
            User user = new User();
            user.setUsername(registerDTO.getUsername());
            user.setPassword(MD5Util.encrypt(registerDTO.getPassword()));
            user.setPhone(registerDTO.getPhone());
            user.setRole("leader");
            user.setStatus(1); // 默认启用
            userMapper.insert(user);
            
            // 创建团长信息
            Leader leader = new Leader();
            leader.setUserId(user.getId());
            leader.setName(registerDTO.getName());
            leader.setPhone(registerDTO.getPhone());
            leader.setAddress(registerDTO.getAddress());
            leader.setStatus(1); // 默认启用
            
            leaderMapper.insert(leader);
            return ResponseUtil.created();
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ResultCode.SERVER_ERROR, "团长添加失败: " + e.getMessage());
        }
    }

    /**
     * 修改团长
     * @param leader 团长信息
     * @return 操作结果
     */
    @PutMapping
    public ResponseEntity<Result<Void>> update(@Valid @RequestBody Leader leader) {
        if (leader.getId() == null) {
            return ResponseUtil.badRequest("ID不能为空");
        }

        Leader existLeader = leaderMapper.selectById(leader.getId());
        if (existLeader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        // 检查手机号是否已被其他团长使用
        if (!existLeader.getPhone().equals(leader.getPhone())) {

            // 更新关联用户的手机号
            User user = userMapper.selectById(existLeader.getUserId());
            if (user != null) {
                user.setPhone(leader.getPhone());
                userMapper.updateById(user);
            }
        }

        // 如果状态发生变化，同步更新用户状态
        if (!existLeader.getStatus().equals(leader.getStatus())) {
            User user = userMapper.selectById(existLeader.getUserId());
            if (user != null) {
                user.setStatus(leader.getStatus());
                userMapper.updateById(user);
            }
        }

        leaderMapper.updateById(leader);
        return ResponseUtil.success();
    }

    /**
     * 删除团长
     * @param id 团长ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> delete(@PathVariable Long id) {
        Leader leader = leaderMapper.selectById(id);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        // 删除关联的用户账号
        userMapper.deleteById(leader.getUserId());

        leaderMapper.deleteById(id);
        return ResponseUtil.success();
    }

    /**
     * 更新团长状态
     * @param id 团长ID
     * @param status 状态值（0-禁用，1-启用）
     * @return 操作结果
     */
    @PutMapping("/status")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        Leader leader = leaderMapper.selectById(id);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        // 更新团长状态
        Leader updateLeader = new Leader();
        updateLeader.setId(id);
        updateLeader.setStatus(status);
        leaderMapper.updateById(updateLeader);

        // 同步更新用户状态
        User updateUser = new User();
        updateUser.setId(leader.getUserId());
        updateUser.setStatus(status);
        userMapper.updateById(updateUser);

        return ResponseUtil.success();
    }

    /**
     * 获取团长订单统计
     * @param leaderId 团长ID
     * @return 订单统计信息
     */
    @GetMapping("/order-stats")
    public ResponseEntity<Result<LeaderOrderStatsView>> getOrderStats(@RequestParam Long leaderId) {
        // 检查团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        LeaderOrderStatsView stats = leaderOrderStatsViewMapper.selectById(leaderId);
        if (stats == null) {
            // 如果没有数据，创建一个空的统计对象
            stats = new LeaderOrderStatsView();
            stats.setLeaderId(leaderId);
            stats.setLeaderName(leader.getName());
            stats.setOrderCount(0);
            stats.setTotalAmount(BigDecimal.ZERO);
            stats.setCompletedCount(0);
            stats.setCompletedAmount(BigDecimal.ZERO);
        }
        return ResponseUtil.success(stats);
    }

    /**
     * 获取团长佣金统计
     * @param leaderId 团长ID
     * @return 佣金统计信息
     */
    @GetMapping("/commission-stats")
    public ResponseEntity<Result<CommissionStatsView>> getCommissionStats(@RequestParam Long leaderId) {
        // 检查团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        CommissionStatsView stats = commissionStatsViewMapper.selectById(leaderId);
        if (stats == null) {
            // 如果没有数据，创建一个空的统计对象
            stats = new CommissionStatsView();
            stats.setLeaderId(leaderId);
            stats.setLeaderName(leader.getName());
            stats.setTotalCommission(BigDecimal.ZERO);
            stats.setSettledCommission(BigDecimal.ZERO);
            stats.setUnsettledCommission(BigDecimal.ZERO);
        }
        return ResponseUtil.success(stats);
    }

    /**
     * 获取团长仪表盘数据
     * @param leaderId 团长ID
     * @return 仪表盘数据
     */
    @GetMapping("/dashboard")
    public ResponseEntity<Result<Map<String, Object>>> getDashboardData(@RequestParam Long leaderId) {
        // 查询团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        // 统计数据
        Map<String, Object> statistics = new HashMap<>();

        // 1. 订单总数
        Long orderCount = orderMapper.selectCount(
                Wrappers.<Order>lambdaQuery().eq(Order::getLeaderId, leaderId)
        );
        statistics.put("orderCount", orderCount);

        // 2. 订单总金额
        List<Order> orders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery().eq(Order::getLeaderId, leaderId)
        );
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Order order : orders) {
            totalAmount = totalAmount.add(order.getTotalAmount());
        }
        statistics.put("totalAmount", totalAmount);

        // 3. 佣金总额
        List<Commission> commissions = commissionMapper.selectList(
                Wrappers.<Commission>lambdaQuery().eq(Commission::getLeaderId, leaderId)
        );
        BigDecimal totalCommission = BigDecimal.ZERO;
        BigDecimal unsettledCommission = BigDecimal.ZERO;
        for (Commission commission : commissions) {
            totalCommission = totalCommission.add(commission.getAmount());
            if (commission.getStatus() == 0) { // 未结算
                unsettledCommission = unsettledCommission.add(commission.getAmount());
            }
        }
        statistics.put("totalCommission", totalCommission);
        statistics.put("unsettledCommission", unsettledCommission);

        // 4. 所有订单列表（最近10条）
        List<Order> recentOrders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                        .eq(Order::getLeaderId, leaderId)
                        .orderByDesc(Order::getCreateTime)
                        .last("LIMIT 10") // 最多10条
        );

        Map<String, Object> result = new HashMap<>();
        result.put("statistics", statistics);
        result.put("allOrders", recentOrders);

        return ResponseUtil.success(result);
    }

    /**
     * 获取团长佣金详情
     * @param leaderId 团长ID
     * @return 佣金详情
     */
    @GetMapping("/commission-detail")
    public ResponseEntity<Result<Map<String, Object>>> getCommissionDetail(@RequestParam Long leaderId) {
        // 检查团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }

        // 查询佣金记录
        List<Commission> commissions = commissionMapper.selectList(
                Wrappers.<Commission>lambdaQuery()
                        .eq(Commission::getLeaderId, leaderId)
                        .orderByDesc(Commission::getCreateTime)
        );

        // 计算统计数据
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal settledAmount = BigDecimal.ZERO;
        BigDecimal unsettledAmount = BigDecimal.ZERO;

        for (Commission commission : commissions) {
            totalAmount = totalAmount.add(commission.getAmount());
            if (commission.getStatus() == 1) { // 已结算
                settledAmount = settledAmount.add(commission.getAmount());
            } else { // 未结算
                unsettledAmount = unsettledAmount.add(commission.getAmount());
            }
        }

        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalAmount", totalAmount);
        statistics.put("settledAmount", settledAmount);
        statistics.put("unsettledAmount", unsettledAmount);

        Map<String, Object> result = new HashMap<>();
        result.put("statistics", statistics);
        result.put("commissions", commissions);

        return ResponseUtil.success(result);
    }
}
